import React, { useState, useEffect, useCallback, useRef } from 'react';
import { FileItem } from '@/utils/api';
import api from '@/utils/api';

// 从URL提取视频封面（用于已上传的视频）
const extractVideoThumbnailFromUrl = (videoUrl: string): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.muted = true;
    video.playsInline = true;
    video.crossOrigin = 'anonymous'; // 允许跨域
    
    // 等待视频元数据加载完成
    video.onloadeddata = () => {
      try {
        // 设置视频时间到第一帧（0.1秒，避免黑屏）
        video.currentTime = 0.1;
      } catch (error) {
        console.warn('设置视频时间失败，使用默认时间:', error);
        video.currentTime = 0;
      }
    };
    
    // 当视频跳转到指定时间后
    video.onseeked = () => {
      try {
        // 创建Canvas
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth || 320;
        canvas.height = video.videoHeight || 240;
        const ctx = canvas.getContext('2d');
        
        if (!ctx) {
          reject(new Error('无法创建Canvas上下文'));
          return;
        }
        
        // 将视频帧绘制到Canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 将Canvas转换为Blob
        canvas.toBlob((blob) => {
          if (blob) {
            console.log('✅ 视频封面提取成功（从URL），大小:', blob.size, 'bytes');
            resolve(blob);
          } else {
            reject(new Error('Canvas转换为Blob失败'));
          }
        }, 'image/jpeg', 0.8);
      } catch (error) {
        reject(error);
      }
    };
    
    video.onerror = () => {
      reject(new Error('视频加载失败'));
    };
    
    // 设置超时
    setTimeout(() => {
      if (video.readyState < 2) {
        reject(new Error('视频加载超时'));
      }
    }, 10000);
    
    video.src = videoUrl;
  });
};

const Favorites: React.FC = () => {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentCategory, setCurrentCategory] = useState('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null);
  const [thumbnailCache, setThumbnailCache] = useState<Record<string, string>>({}); // 缓存提取的封面
  const generatingThumbnailsRef = useRef<Set<string>>(new Set()); // 正在生成封面的文件ID集合

  const categories = [
    { key: 'all', label: '全部文件', icon: '📁' },
    { key: 'image', label: '图片', icon: '🖼️' },
    { key: 'video', label: '视频', icon: '🎬' },
    { key: 'audio', label: '音频', icon: '🎵' },
    { key: 'document', label: '文档', icon: '📄' },
    { key: 'other', label: '其他', icon: '📦' },
  ];

  // 加载收藏文件
  const loadFavorites = useCallback(async () => {
    setLoading(true);
    try {
      const response = await api.fileManager.getFavorites({
        page,
        limit: 20,
        category: currentCategory === 'all' ? undefined : currentCategory,
      });

      if (response.data) {
        setFiles(response.data.files);
        setTotal(response.data.total);
        
        // 自动为没有封面的视频生成封面（后台异步处理，不阻塞UI）
        const videosWithoutThumbnail = response.data.files.filter(
          file => file.category === 'video' && !file.thumbnailUrl && !generatingThumbnailsRef.current.has(file._id)
        );
        
        if (videosWithoutThumbnail.length > 0) {
          // 异步生成封面，不阻塞UI
          videosWithoutThumbnail.forEach(async (video) => {
            // 标记为正在生成
            generatingThumbnailsRef.current.add(video._id);
            
            try {
              const videoUrl = `http://localhost:3000${video.url}`;
              console.log('🎬 开始为收藏视频提取封面:', video.filename);
              
              // 提取封面
              const thumbnailBlob = await extractVideoThumbnailFromUrl(videoUrl);
              
              // 转换为base64用于显示
              const reader = new FileReader();
              reader.onloadend = () => {
                const base64String = reader.result as string;
                setThumbnailCache(prev => ({
                  ...prev,
                  [video._id]: base64String
                }));
                generatingThumbnailsRef.current.delete(video._id);
              };
              reader.readAsDataURL(thumbnailBlob);
              
              // 上传封面到服务器
              const thumbnailFile = new File([thumbnailBlob], `thumb-${video.filename}.jpg`, { type: 'image/jpeg' });
              const thumbnailFormData = new FormData();
              thumbnailFormData.append('files', thumbnailFile);
              thumbnailFormData.append('userId', 'user123');
              thumbnailFormData.append('userName', '测试用户');
              thumbnailFormData.append('isThumbnail', 'true');
              
              const thumbnailResponse = await api.fileManager.upload(thumbnailFormData);
              if (thumbnailResponse.success && thumbnailResponse.data && thumbnailResponse.data.length > 0) {
                const thumbnailUrl = thumbnailResponse.data[0].url;
                console.log('✅ 收藏视频封面上传成功:', thumbnailUrl);
                
                // 更新文件的thumbnailUrl
                try {
                  await api.fileManager.updateFile(video._id, { thumbnailUrl });
                  console.log('✅ 文件封面URL更新成功');
                  // 刷新列表以显示封面
                  setTimeout(() => {
                    loadFavorites();
                  }, 1000);
                } catch (error) {
                  console.warn('⚠️ 更新文件封面URL失败:', error);
                }
              }
            } catch (error) {
              console.error(`为视频 ${video.filename} 生成封面失败:`, error);
              generatingThumbnailsRef.current.delete(video._id);
            }
          });
        }
      }
    } catch (error) {
      console.error('加载收藏列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [page, currentCategory]);

  useEffect(() => {
    loadFavorites();
  }, [loadFavorites]);

  // 取消收藏
  const handleUnfavorite = async (fileId: string) => {
    try {
      await api.fileManager.unfavoriteFile(fileId);
      loadFavorites();
    } catch (error) {
      console.error('取消收藏失败:', error);
      alert('取消收藏失败');
    }
  };

  // 下载文件
  const handleDownload = (file: FileItem) => {
    window.open(file.url, '_blank');
  };

  // 预览文件
  const handlePreview = (file: FileItem) => {
    if (file.category === 'image' || file.category === 'video') {
      setPreviewFile(file);
    } else {
      window.open(file.url, '_blank');
    }
  };

  // 获取文件图标
  const getFileIcon = (file: FileItem) => {
    if (file.category === 'image') {
      return file.url;
    }
    const iconMap: Record<string, string> = {
      image: '🖼️',
      video: '🎬',
      audio: '🎵',
      document: '📄',
      other: '📦',
    };
    return iconMap[file.category] || '📄';
  };

  return (
    <div className="h-full flex flex-col bg-gray-50">
      {/* 头部 */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
              <span>⭐</span>
              我的收藏
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              共 {total} 个收藏文件
            </p>
          </div>

          {/* 视图切换 */}
          <div className="flex gap-2">
            <button
              onClick={() => setViewMode('grid')}
              className={`px-3 py-2 rounded-lg transition-colors ${
                viewMode === 'grid'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              网格
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`px-3 py-2 rounded-lg transition-colors ${
                viewMode === 'list'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              列表
            </button>
          </div>
        </div>

        {/* 分类筛选 */}
        <div className="flex gap-2 flex-wrap">
          {categories.map((cat) => (
            <button
              key={cat.key}
              onClick={() => setCurrentCategory(cat.key)}
              className={`px-4 py-2 rounded-lg transition-colors ${
                currentCategory === cat.key
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              <span className="mr-1">{cat.icon}</span>
              {cat.label}
            </button>
          ))}
        </div>
      </div>

      {/* 文件列表 */}
      <div className="flex-1 overflow-y-auto p-6">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-gray-500">加载中...</div>
          </div>
        ) : files.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-gray-400">
            <span className="text-6xl mb-4">⭐</span>
            <p className="text-lg">暂无收藏文件</p>
            <p className="text-sm mt-2">点击文件上的星标即可收藏</p>
          </div>
        ) : viewMode === 'grid' ? (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
            {files.map((file) => (
              <div
                key={file._id}
                className="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden group relative"
              >
                {/* 文件预览 */}
                <div
                  className="h-40 bg-gray-100 flex items-center justify-center cursor-pointer relative overflow-hidden"
                  onClick={() => handlePreview(file)}
                >
                  {file.category === 'image' ? (
                    <img
                      src={`http://localhost:3000${file.url}`}
                      alt={file.filename}
                      className="w-full h-full object-cover"
                    />
                  ) : file.category === 'video' && (file.thumbnailUrl || thumbnailCache[file._id]) ? (
                    <div className="relative w-full h-full bg-gray-100">
                      <img
                        src={thumbnailCache[file._id] || `http://localhost:3000${file.thumbnailUrl}`}
                        alt={file.filename}
                        className="w-full h-full object-cover bg-gray-100"
                        crossOrigin="anonymous"
                        onError={(e) => {
                          // 如果封面加载失败，显示默认图标
                          const target = e.currentTarget;
                          target.style.display = 'none';
                          const parent = target.parentElement;
                          if (parent && !parent.querySelector('.fallback-icon')) {
                            const fallback = document.createElement('div');
                            fallback.className = 'fallback-icon w-full h-full flex items-center justify-center bg-gray-100';
                            fallback.innerHTML = '<span class="text-5xl">🎬</span>';
                            parent.appendChild(fallback);
                          }
                        }}
                      />
                      {/* 播放按钮覆盖层 */}
                      <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                        <div className="bg-white bg-opacity-80 rounded-full p-2 shadow-lg transform transition-all duration-300 group-hover:scale-110 group-hover:bg-opacity-100">
                          <svg 
                            className="w-6 h-6 text-gray-800 ml-0.5" 
                            fill="currentColor" 
                            viewBox="0 0 24 24"
                          >
                            <path d="M8 5v14l11-7z"/>
                          </svg>
                        </div>
                      </div>
                      {/* 悬停时的遮罩层 */}
                      <div className="absolute inset-0 bg-black opacity-0 group-hover:opacity-20 transition-opacity duration-300 pointer-events-none"></div>
                    </div>
                  ) : (
                    <span className="text-5xl">{getFileIcon(file)}</span>
                  )}
                </div>

                {/* 收藏标记 */}
                <button
                  onClick={() => handleUnfavorite(file._id)}
                  className="absolute top-2 right-2 text-2xl opacity-0 group-hover:opacity-100 transition-opacity"
                  title="取消收藏"
                >
                  ⭐
                </button>

                {/* 文件信息 */}
                <div className="p-3">
                  <h3 className="text-sm font-medium text-gray-800 truncate" title={file.filename}>
                    {file.filename}
                  </h3>
                  <div className="flex items-center justify-between mt-2 text-xs text-gray-500">
                    <span>{file.sizeFormatted || formatFileSize(file.size)}</span>
                    <span>{new Date(file.favoriteAt!).toLocaleDateString()}</span>
                  </div>
                  
                  {/* 操作按钮 */}
                  <div className="mt-3 flex gap-2">
                    <button
                      onClick={() => handleDownload(file)}
                      className="flex-1 px-3 py-1.5 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
                    >
                      下载
                    </button>
                    <button
                      onClick={() => handleUnfavorite(file._id)}
                      className="px-3 py-1.5 text-xs bg-gray-100 text-gray-600 rounded hover:bg-gray-200"
                    >
                      取消
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          // 列表视图
          <div className="bg-white rounded-lg shadow-sm overflow-hidden">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">文件名</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">大小</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">收藏时间</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">操作</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {files.map((file) => (
                  <tr key={file._id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 flex items-center gap-3">
                      <span className="text-2xl">{getFileIcon(file)}</span>
                      <span className="text-sm text-gray-800 truncate max-w-md" title={file.filename}>
                        {file.filename}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600">
                      {file.sizeFormatted || formatFileSize(file.size)}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600">
                      {new Date(file.favoriteAt!).toLocaleString()}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handlePreview(file)}
                          className="px-3 py-1 text-xs bg-gray-100 text-gray-600 rounded hover:bg-gray-200"
                        >
                          预览
                        </button>
                        <button
                          onClick={() => handleDownload(file)}
                          className="px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
                        >
                          下载
                        </button>
                        <button
                          onClick={() => handleUnfavorite(file._id)}
                          className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
                        >
                          取消收藏
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* 分页 */}
        {total > 20 && (
          <div className="mt-6 flex justify-center gap-2">
            <button
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
              className="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <span className="px-4 py-2 bg-white border border-gray-300 rounded-lg">
              {page} / {Math.ceil(total / 20)}
            </span>
            <button
              onClick={() => setPage(page + 1)}
              disabled={page >= Math.ceil(total / 20)}
              className="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        )}
      </div>

      {/* 预览弹窗 */}
      {previewFile && (
        <div
          className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50"
          onClick={() => setPreviewFile(null)}
        >
          <div className="max-w-4xl max-h-[90vh] relative">
            <button
              onClick={() => setPreviewFile(null)}
              className="absolute -top-10 right-0 text-white text-2xl hover:text-gray-300"
            >
              ✕
            </button>
            {previewFile.category === 'image' ? (
              <img src={`http://localhost:3000${previewFile.url}`} alt={previewFile.filename} className="max-w-full max-h-[90vh]" />
            ) : previewFile.category === 'video' ? (
              <video src={`http://localhost:3000${previewFile.url}`} controls className="max-w-full max-h-[90vh]" />
            ) : null}
          </div>
        </div>
      )}
    </div>
  );
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
};

export default Favorites;

